/*************************************************************************
	> File Name: monolith/interface/sql/sql_base.cc
	> Author: dzhang
	> Mail: dong.zhang@ingenic.com 
	> Created Time: Thu 04 Feb 2021 10:33:12 AM CST
 ************************************************************************/

#include "monolith/interface/sql/sql_base.h"
#include "glog/logging.h"
#include <iostream>

CC_NAME_SPACE_BEGIN
namespace sql {

int SQLBase::open(std::string db_file) {
    try {
        db_ = new SQLite::Database(db_file,
                SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE);
    } catch (std::exception &e) {
        LOG(ERROR)<< "SQLite exception: " << e.what();
        return EXIT_FAILURE;
    }
    return 0;
}

int SQLBase::close() {
    if (db_) {
        delete db_;
    }
    return 0;
}

int SQLBase::exec(const char *apQueries) {
    int state = 0;
    try {
        state = db_->exec(apQueries);
    } catch (std::exception &e) {
        LOG(ERROR)<< "SQLite exception: " << e.what() << ", "
        << std::string(apQueries);
    }
    return state;
}

int SQLBase::exec(const std::string &aQueries) {
    return exec(aQueries.c_str());
}

SQLite::Column SQLBase::execAndGet(const char *apQuery) {
    try {
        auto colum = db_->execAndGet(apQuery);
        return colum;
    } catch (std::exception &e) {
        LOG(ERROR)<< "SQLite exception: " << e.what() << ", "
        << std::string(apQuery);
        exit(0);
    }
}

SQLite::Column SQLBase::execAndGet(const std::string& apQuery) {
    return execAndGet(apQuery.c_str());
}

std::vector<SQLite::Column> SQLBase::query(const char* apQuery) {
    SQLite::Statement query_data(*db_, apQuery);
    std::vector<SQLite::Column> res;
    // query_data.bind(1, 2);
    while (query_data.executeStep()) {
        for (int i = 0; i < query_data.getColumnCount(); i++) {
            LOG(INFO)<< query_data.getColumnCount();
            res.push_back(query_data.getColumn(1));
        }
    }
    return res;
}

std::vector<SQLite::Column> SQLBase::query(const std::string& apQuery) {
    return query(apQuery.c_str());
}

} // namespace sql
CC_NAME_SPACE_END




